package com.ciwong.epaper.modules.me.presenter;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.MsgPostBean;
import com.ciwong.epaper.bean.MsgtypeBean;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.ui.JsonParserUtil;
import com.ciwong.epaper.modules.me.ui.interfaces.IHomeWorkFragment;
import com.ciwong.epaper.modules.me.util.AddPointTypes;
import com.ciwong.epaper.modules.msg.bean.MessageInfo;
import com.ciwong.epaper.modules.msg.bean.MsgTypeConfig;
import com.ciwong.epaper.modules.msg.dao.MsgDao;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class HomeWorkRelatPresenter implements IHomeWorkRelatPresenter {

    private final IHomeWorkFragment homeWorkFragment;
    private  Activity mActivity;
    private  EApplication mApplication;
    /**
     * 更新消息数值
     */
    private int msgNum;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                msgNum = 0;
            }
            return homeWorkFragment.handleMessage(msg);
        }
    });


    public HomeWorkRelatPresenter(IHomeWorkFragment homeWorkFragment, Activity activity, EApplication application){
        this.homeWorkFragment = homeWorkFragment;
        this.mActivity = activity;
        this.mApplication = application;

    }
    public Handler getHandler() {
        return mHandler;
    }
    public void signIn() {
        final UserInfoBase userInfoBase = mApplication.getUserInfoBase();
        if (userInfoBase==null)return;
        Calendar calendar = Calendar.getInstance();
        //现在的日期(几号)
        final int day = calendar.get(Calendar.DAY_OF_MONTH);
        //上次签到的日期(几号)
        int preDay = CWSys.getSharedInt(EConstants.SHARE_KEY_DATA_DAY_SIGN_IN + userInfoBase.getUserId(), -1);
        if (day != preDay) {
            MeDao.getInstance().addPoint(userInfoBase.getUserId() + "", userInfoBase.getRealName(), AddPointTypes.SIGN_IN, null, new BaseCallBack() {
                @Override
                public void failed(int errorCode, Object data) {
                }

                @Override
                public void failed(Object data) {
                }

                public void success(Object string) {
//                    CWSys.setSharedInt(EConstants.SHARE_KEY_DATA_DAY_SIGN_IN + userInfoBase.getUserId(), day);
//                    String strToast = "签到成功\n+" + string + "积分";
//                    SpannableString spannableString = new SpannableString(strToast);
//                    ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#52CC8F"));
//                    spannableString.setSpan(colorSpan, strToast.indexOf("+"), strToast.indexOf("+") + 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//                    ToastUtil.INSTANCE.toastCenter(EApplication.getInstance(), spannableString, Toast.LENGTH_LONG, R.mipmap.ic_success);
                }
            });
        }
    }

    /**
     * 获取本地未读消息数量
     */
    public void getLocalMsgCount() {

        SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_NO_READ_MSG_COUNT_NEW, new BaseCallBack() {
            @Override
            public void success(Object data) {
                if (data != null) {
                    List<MessageInfo> counts = (List<MessageInfo>) data;
                    sendHandlerMsgNum(counts);
                }
                //先从本地获取数据，再从网络获取数据
                getNetMsgCount();
            }

            @Override
            public void failed(int errorCode, Object data) {
                getNetMsgCount();
            }

            @Override
            public void failed(Object data) {
                getNetMsgCount();
            }
        });

    }

    /**
     * 获取网络未读消息数量
     */
    public void getNetMsgCount() {
        UserInfoBase userInfoBase = mApplication.getUserInfoBase();
        if (null != userInfoBase) {

            boolean isGetSuccessFulOnce = ESystem.getSharedBoolean(EConstants.SHARE_KEY_MSG_HAS_GET_SUCESSFUL_ONCE + userInfoBase.getUserId(), false);

            //首先要请求一次getNetMsgList接口，本地保存msgId
            if (!isGetSuccessFulOnce) {
                getNetMsgList(getMsgPostBean(userInfoBase.getUserId()));
                return;
            }
            MsgPostBean msgPostBean = getMsgPostBean(userInfoBase.getUserId());
            String postJson = JsonParserUtil.toJson(msgPostBean);
            MsgDao.getInstance().getNetMsgCountNew(postJson, new BaseExtCallBack(mActivity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                @Override
                public void failed(int errorCode, Object data) {
                    super.failed(errorCode, data);
                    ToastUtil.INSTANCE.toastCenterErrorWithErrorCode("获取未读消息失败", errorCode);
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MESSAGE, data == null ? "" : "失败信息：" + data.toString(), "获取未读消息失败");
                }

                @Override
                public void failed(Object data) {
//                    ToastUtil.INSTANCE.toastCenterError("获取未读消息失败");
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MESSAGE, data == null ? "" : "失败信息：" + data.toString(), "获取未读消息失败");
                }

                public void success(Object data) {
                    if (data != null) {
                        List<MessageInfo> counts = (List<MessageInfo>) data;
                        sendHandlerMsgNum(counts);
                        //从网络获取成功后保存在本地
                        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_NO_READ_MSG_COUNT_NEW, (Serializable) counts);
                    }
                }
            });
        }
    }



    private void getNetMsgList(MsgPostBean msgPostBean) {
        final UserInfoBase userInfoBase = mApplication.getUserInfoBase();
        if (null != userInfoBase) {
            String postJson = JsonParserUtil.toJson(msgPostBean);
            MsgDao.getInstance().getMessageListNew(postJson, new BaseExtCallBack(mActivity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                @Override
                public void failed(int errorCode, Object data) {
                    super.failed(errorCode, data);
                }

                @Override
                public void failed(Object data) {

                }

                public void success(Object data) {
                    if (data != null) {
                        ArrayList<MessageInfo> infos = (ArrayList<MessageInfo>) data;
                        if (infos != null && infos.size() > 0) {
                            for (int i = 0; i < infos.size(); i++) {
                                MessageInfo info = infos.get(i);
                                if (MsgTypeConfig.MSG_SERVICE == info.getMsgGroup()) {
                                    ESystem.setSharedInt(EConstants.SHARE_KEY_MSG_TYPE_SERVICE_MSG_GROUP_ID + userInfoBase.getUserId(), info.getMsgId());
                                } else {
                                    ESystem.setSharedInt(EConstants.SHARE_KEY_MSG_TYPE_HOMEWORK_MSG_GROUP_ID + userInfoBase.getUserId(), info.getMsgId());

                                }
                            }
                            ESystem.setSharedBoolean(EConstants.SHARE_KEY_MSG_HAS_GET_SUCESSFUL_ONCE + userInfoBase.getUserId(), true);
                        }
                    }
                }
            });
        }

    }

    private MsgPostBean getMsgPostBean(long userId) {
        MsgPostBean msgPostBean = new MsgPostBean();
        msgPostBean.setBrandId(EApplication.BRAND_ID);


        msgPostBean.setUserId(userId);
        //作业类型
        MsgtypeBean msgtypeListBeanHomework = new MsgtypeBean();
        int homeworkMsgId = ESystem.getSharedInt(EConstants.SHARE_KEY_MSG_TYPE_HOMEWORK_MSG_GROUP_ID + userId, 0);

        msgtypeListBeanHomework.setMsgId(homeworkMsgId);
        msgtypeListBeanHomework.setMsgGroup(MsgTypeConfig.MSG_WORK_NOTIFICATION);

        //服务类型
        MsgtypeBean msgtypeListBeanMail = new MsgtypeBean();
        int mainMsgId = ESystem.getSharedInt(EConstants.SHARE_KEY_MSG_TYPE_SERVICE_MSG_GROUP_ID + userId, 0);
        msgtypeListBeanMail.setMsgId(mainMsgId);
        msgtypeListBeanMail.setMsgGroup(MsgTypeConfig.MSG_SERVICE);

        List<MsgtypeBean> msgtypeListBeans = new ArrayList<>();
        msgtypeListBeans.add(msgtypeListBeanHomework);
        msgtypeListBeans.add(msgtypeListBeanMail);
        msgPostBean.setMsgtypeList(msgtypeListBeans);
        return msgPostBean;
    }

    /**
     * 发送消息数值
     */
    private void sendHandlerMsgNum(List<MessageInfo> counts) {

        for (MessageInfo count : counts) {
            msgNum += count.getMsgCount();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                Bundle bundle = new Bundle();
                bundle.putInt("msgNum", msgNum);
                message.setData(bundle);
                mHandler.sendMessage(message);
            }
        }).start();
    }




















}
